import React, { useEffect, useState } from 'react';
import {
    Row,
    Col,
    Form,
    Drawer,
    Button,
    Input,
    Select,
    Switch,
    InputNumber,
    message,
    Divider
} from 'antd';
import { history } from 'umi';
import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
import moment from 'moment';
import zhCN from 'antd/es/date-picker/locale/zh_CN';
import style from './AddForm.css';

const { Option } = Select;
const layout = {
    labelCol: { span: 7 },
    wrapperCol: { span: 17 },
};

function AddDrawer({
    userList,
    info,
    machTypes,
    onClose,
    onDispatch,
}) {
    const [fileList, setFileList] = useState([]);
    const [currentType, setCurrentType] = useState(null);
    const [modelList, setModelList] = useState([]);
    const [showList, setShowList] = useState([]);
    const [value, setValue] = useState('');
    const [form] = Form.useForm();
    
    const handleChange = ({ fileList })=>{
        setFileList(fileList);
    }
    const handlePreview = (file) => {
        // file.thumbUrl 默认编译成200*200像素的64位字符串, 用FileReader重新解析
        if (!file.preview) {
            getBase64(file.originFileObj).then((data) => {
                file.preview = data;
                setPreviewInfo({
                    visible: true,
                    img: data,
                    title: file.name,
                });
            });
        } else {
            setPreviewInfo({
                visible: true,
                img: file.preview,
                title: file.name,
            });
        }
    };
    const handleBeforeUpload = (file) => {
        const isJPG = file.type === 'image/jpeg';
        const isJPEG = file.type === 'image/jpeg';
        const isGIF = file.type === 'image/gif';
        const isPNG = file.type === 'image/png';
        if (!(isJPG || isJPEG || isGIF || isPNG)) {
            message.error('只能上传JPG 、JPEG 、GIF、 PNG格式的图片');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('产品图不能超过2M');
        }
        return false;
    };
    const uploadButton = (
        <div>
            <PlusOutlined />
            <div className="ant-upload-text">上传产品图</div>
        </div>
    );
    
    useEffect(() => {
        if ( info.visible ) {
            if (info.forEdit) {
                setCurrentType(info.current.energyType);
                form.setFieldsValue({ ...info.current, machType:info.current.energyType + '' });
                // form.setFieldsValue({
                //     ...info.current,
                //     equipmentProductionDate: moment(info.current.equipmentProductionDate),
                //     equipmentMaintenanceEndDate: moment(
                //         info.current.equipmentMaintenanceEndDate,
                //     ),
                // });
                // // 显示产品图的缩略图
                // if (equipmentPhotoPath) {
                //     let config = window.g;
                //     setFileList([
                //         {
                //             uid: '-1',
                //             name: 'image.png',
                //             status: 'done',
                //             prevPath: equipmentPhotoPath,
                //             url: `https://${config.apiHost}/upload/getFileByPath?filePath=${equipmentPhotoPath}`,
                //         },
                //     ]);
                // } else {
                //     setFileList([]);
                // }
            } else {
                form.resetFields();
                form.setFieldsValue({ machType:null, disable:true });
                setFileList([]);
            }
        }
    }, [info]);
    useEffect(()=>{
        if ( machTypes.length ) {
            setCurrentType(machTypes[0].typeCode);
        }
    },[machTypes])
    useEffect(()=>{
        if( currentType ) {
            new Promise((resolve, reject)=>{
                onDispatch({ type:'mach/fetchModelListByEnergy', payload:{ resolve, reject, energyType:currentType }})
            })
            .then((data)=>{
                setModelList(data);
                setShowList(data);         
            })
            setValue('');
            if ( !info.forEdit ) {
                form.setFieldsValue({ modelId:null });
            }
        }
    },[currentType]);
    
    return (
        <Drawer
            width="46%"
            open={info.visible ? true : false}
            className={style['custom-drawer']}
            onClose={onClose}
            title={info.forEdit ? '更新设备档案' : '新建设备档案'}
            footer={(
                <div style={{ display:'flex', justifyContent:'flex-end' }}>
                    <Button style={{ marginRight:'0.5rem' }} onClick={onClose}>取消</Button>
                    <Button type='primary' onClick={()=>{
                        form.validateFields()
                        .then(values=>{
                            if ( info.forEdit ) {
                                values.machId = info.current.machId;
                            }
                            values.disable = values.disable ? 1 : 0;
                            values.energyType = currentType;
                            new Promise((resolve, reject)=>{
                                onDispatch({ type:'mach/addMachAsync', payload:{ resolve, reject, values, forEdit:info.forEdit }})
                            })
                            .then(()=>{
                                message.success(`${info.forEdit ? '更新' : '添加'}设备档案成功` );
                                onClose();
                            })
                            .catch(msg=>message.error(msg));
                        })
                        
                    }}>确定</Button>
                </div>
            )}
        >
            {/* 基础信息 */}
            <div
                style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    borderBottom: '1px solid #f0f0f0',
                    marginBottom: '2rem',
                    paddingBottom: '0.5rem',
                }}
            >
                <div>基础信息</div>
                {/* {tplList.length ? (
                    <div>
                        <span>模板选择 : </span>
                        <Select
                            size="small"
                            style={{ width: '180px' }}
                            onChange={(value) => {
                                let data =
                                    tplList.filter((i) => i.equipmentTemplateId === value)[0] ||
                                    {};
                                form.setFieldsValue({
                                    ...data,
                                    equipmentProductionDate: moment(data.equipmentProductionDate),
                                    equipmentMaintenanceEndDate: moment(
                                        data.equipmentMaintenanceEndDate,
                                    ),
                                });
                            }}
                        >
                            {tplList.map((item) => (
                                <Option
                                    key={item.equipmentTemplateId}
                                    value={item.equipmentTemplateId}
                                >
                                    {item.equipmentTemplateName}
                                </Option>
                            ))}
                        </Select>
                    </div>
                ) : null} */}
            </div>
            <Form className={style['form-container']} form={form} {...layout}>             
                <Row gutter={24}>
                    <Col span={12}>
                        <Form.Item
                            label="设备类型"
                            name='machType'
                            rules={[{ required: true, message: '该字段不能为空' }]}
                        >
                            <Select onChange={value=>setCurrentType(value)} disabled={info.forEdit ? true : false }>
                                {
                                    machTypes.map(item=>(
                                        <Option key={item.typeCode} value={item.typeCode}>{ item.typeName }</Option>
                                    ))
                                }
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            label="设备型号"
                            name="modelId"
                            rules={[{ required: true, message: '该字段不能为空' }]}
                        >
                            <Select disabled={info.forEdit ? true : false } dropdownRender={(menu)=>(
                                <>
                                    { menu }
                                    <Divider style={{ margin:'8px 0'}} />
                                    <div style={{ display:'flex', alignItems:'center', padding:'0 1rem' }}>
                                        <Input
                                            style={{ flex:'1' }}
                                            placeholder="输入设备名查询"
                                            value={value}
                                            onChange={e=>setValue(e.target.value)}
                                            allowClear                                
                                        />
                                        <Button type="primary" icon={<SearchOutlined />} onClick={()=>{
                                            if ( value ) {
                                                setShowList(showList.filter(i=>i.modelDesc.includes(value) ));
                                            } else {
                                                setShowList(modelList);
                                            }
                                        }}>查询</Button>
                                    </div>                            
                                </>
                            )}>
                                {
                                    showList.map((item)=>(
                                        <Option key={item.modelId} value={item.modelId}>{ item.modelDesc }</Option>
                                    ))
                                }
                            </Select>
                        </Form.Item>
                    </Col>
                    
                    <Col span={12}>
                        <Form.Item
                            label="设备名称"
                            name="meterName"
                            rules={[{ required: true, message: '该字段不能为空' }]}
                        >
                            <Input style={{ widht:'100%' }} />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            label="注册码"
                            name="registerCode"
                            rules={[{ required: true, message: '该字段不能为空' }]}
                        >
                            <Input style={{ width:'100%' }} disabled={info.forEdit ? true : false }/>
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            label="采集周期"
                            name="dataPeriod"
                            rules={[{ required: true, message: '该字段不能为空' }]}
                        >
                            <InputNumber style={{ width:'100%' }} min={0} addonAfter='秒' />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            label="mudbus地址"
                            name="mbadr"
                            rules={[{ required: true, message: '该字段不能为空' }]}
                        >
                            <Input style={{ width: '100%' }} />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            label="电流变比"
                            name="ratioCurrent"
                            rules={[{ required: true, message: '该字段不能为空' }]}
                        >
                            <InputNumber style={{ width:'100%' }} />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            label="电压变比"
                            name="ratioVoltage"
                            rules={[{ required: true, message: '该字段不能为空' }]}
                        >
                            <InputNumber style={{ width:'100%' }} />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            label="千分因子系数"
                            name="factor"
                            rules={[{ required: true, message: '该字段不能为空' }]}
                        >
                            <InputNumber style={{ width:'100%' }} />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            label="排序值"
                            name="orderBy"
                            rules={[{ required: true, message: '该字段不能为空' }]}
                        >
                            <InputNumber style={{ width:'100%' }} />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            label="使能"
                            name="disable"
                            valuePropName="checked"
                            rules={[{ required: true, message: '该字段不能为空' }]}
                        >
                            <Switch />
                        </Form.Item>
                    </Col>
                    {/* <Col span={24}>
                        <Form.Item
                            label="设备图片"
                            labelCol={{ span: 3 }}
                            wrapperCol={{ span: 21 }}
                        >
                            <Upload
                                listType="picture-card"
                                fileList={fileList}
                                onChange={handleChange}
                                onPreview={() => { }}
                                beforeUpload={handleBeforeUpload}
                            >
                                {fileList.length === 1 ? null : uploadButton}
                            </Upload>
                        </Form.Item>
                    </Col> */}
                </Row>
            </Form>    
        </Drawer>
    );
}

export default React.memo(AddDrawer);
